﻿using System;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;

namespace DMS.Base
{

    public class DBHelper
    {
        private static Database _defaultDatabase = null;

        public static Database Instance
        {
            get
            {
                if (_defaultDatabase == null)
                {
                    _defaultDatabase = DatabaseFactory.CreateDatabase("DefaultConnection");
                }

                return _defaultDatabase;
            }
        }

        public static DbParameter CreateParamer()
        {
            return Instance.DbProviderFactory.CreateParameter();
        }

        public static DbParameter CreateParamer(string name, object value)
        {
            DbParameter param = Instance.DbProviderFactory.CreateParameter();
            param.ParameterName = name;
            param.Value = value;
            return param;
        }

        private SqlCommand CreateCommand(string sql)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;
            cmd.Connection = _defaultDatabase.CreateConnection() as SqlConnection;
            return cmd;

        }

        private SqlCommand CreateCommand(string sql, DbConnection connection)
        {//多条命令同一个连接用于事务控制
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sql;
            cmd.Connection = connection as SqlConnection;
            return cmd;

        }

        public DataSet GetDataSet(string sql, int pageIndex, int pageSize)
        {
            int firstPage = pageIndex * pageSize;

            SqlCommand cmd = CreateCommand(sql);
            DataSet dataset = new DataSet();
            SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
            dataAdapter.Fill(dataset, firstPage, pageSize, "Table1");
            cmd.Dispose();
            cmd.Connection.Close();
            dataAdapter.Dispose();
            return dataset;

        }

        public static object getValue(object value)
        {
            if (value == null)
                return DBNull.Value;
            return value;
        }

        public static object getGuidValue(Guid value)
        {
            if (value == Guid.Empty)
                return DBNull.Value;
            return value;
        }
    }

}
